package cc.cc4414.spring.mybatis.crypto;

import cn.hutool.extra.spring.SpringUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 数据加解密处理器，可自定义加解密方法，实现ICryptService接口即可
 *
 * @author cc 2021年2月24日
 */
public class CryptHandler extends BaseTypeHandler<String> {
    private static volatile ICryptService iCryptService;

    private void init() {
        if (iCryptService == null) {
            synchronized (CryptHandler.class) {
                if (iCryptService == null) {
                    iCryptService = SpringUtil.getBean(ICryptService.class);
                }
            }
        }
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        init();
        ps.setString(i, iCryptService.encrypt(parameter));
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        init();
        String columnValue = rs.getString(columnName);
        return iCryptService.decrypt(columnValue);
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        init();
        String columnValue = rs.getString(columnIndex);
        return iCryptService.decrypt(columnValue);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        init();
        String columnValue = cs.getString(columnIndex);
        return iCryptService.decrypt(columnValue);
    }
}
